package com.elf.zero.utils;

import android.Manifest;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.nfc.NfcAdapter;
import android.os.Build;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Window;
import android.view.WindowManager;

import androidx.core.app.ActivityCompat;
import androidx.core.content.FileProvider;

import com.elf.zero.config.ConfigManagerImplSp;

import java.io.File;
import java.net.NetworkInterface;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

/**
 * Device 工具类
 * Created by Lidong on 2017/11/30.
 */
public class DeviceUtils {

    private static Context mContext;

    public static void init(Context context) {
        mContext = context;
    }

//    /**
//     * 获取设备ID
//     *
//     * @return IMEI或MEID
//     */
//    public static String getDeviceId() {
//        try {
//            if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.READ_PHONE_STATE)
//                    == PackageManager.PERMISSION_GRANTED) {
//                TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
//                return tm.getDeviceId();
//            } else {
//                return "";
//            }
//        }catch (Exception e){
//            e.printStackTrace();
//            return "";
//        }
//    }

    /**
     * 获取设备ID
     *
     * @return IMEI或MEID或UUID
     */
    public static String getDeviceId() {
        String uuid;

        final TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
        String tmSerial = "", androidId = "", tmDevice = "";

        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.READ_PHONE_STATE)
                == PackageManager.PERMISSION_GRANTED) {
            tmDevice = tm.getDeviceId();
        }

        if (!TextUtils.isEmpty(tmDevice)) {
            uuid = tmDevice;
        } else {
            tmDevice = "";
            if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.READ_PHONE_STATE)
                    == PackageManager.PERMISSION_GRANTED) {
                tmSerial = "" + tm.getSimSerialNumber();
            }
            androidId = "" + android.provider.Settings.Secure.getString(mContext.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
            UUID deviceUuid = new UUID(androidId.hashCode(), ((long) tmDevice.hashCode() << 32) | tmSerial.hashCode());
            uuid = deviceUuid.toString();
        }

        return uuid;
    }

    /**
     * 获取mac地址（有时返回02:00:00:00:00:00）
     *
     * @return mac地址
     */
    public static String getMacAddress() {
        try {
            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface nif : all) {
                if (!nif.getName().equalsIgnoreCase("wlan0")) continue;

                byte[] macBytes = nif.getHardwareAddress();
                if (macBytes == null) {
                    return "";
                }

                StringBuilder res1 = new StringBuilder();
                for (byte b : macBytes) {
                    res1.append(String.format("%02X:", b));
                }

                if (res1.length() > 0) {
                    res1.deleteCharAt(res1.length() - 1);
                }
                return res1.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取设备uuid
     */
    public static String getDeviceUUID() {
        String mac = getMacAddress();
        if (!TextUtils.isEmpty(mac) && !"02:00:00:00:00:00".equals(mac)) {
            return mac;
        }

        String imei = getDeviceId();
        if (!TextUtils.isEmpty(imei)) {
            return imei;
        }

        ConfigManagerImplSp configManagerImplSp = new ConfigManagerImplSp(mContext, "device_uuid");
        String uuid = configManagerImplSp.getString("uuid", "");
        if (!TextUtils.isEmpty(uuid)) {
            return uuid;
        }

        uuid = UUID.randomUUID().toString();
        configManagerImplSp.putString("uuid", uuid);
        return uuid;
    }

    /**
     * 获取电话号码
     *
     * @return 电话号码
     */
    public static String getTelephoneNumber() {
        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.READ_PHONE_STATE)
                == PackageManager.PERMISSION_GRANTED) {
            TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
            String number = tm.getLine1Number();
            return TextUtils.isEmpty(number) ? "" : number;
        } else {
            return "";
        }
    }

    /**
     * 获取网络运营商名称
     *
     * @return 网络运营商名称
     */
    public static String getNetworkOperatorName() {
        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.READ_PHONE_STATE)
                == PackageManager.PERMISSION_GRANTED) {
            TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
            return tm.getNetworkOperatorName();
        } else {
            return "";
        }
    }

    /**
     * 获取设备型号
     *
     * @return 设备型号
     */
    public static String getDeviceModel() {
        return android.os.Build.MODEL;
    }

    /**
     * 是否支持NFC
     *
     * @return 如果支付NFC返回true, 否则返回false
     */
    public static boolean isSupportNFC() {
        return NfcAdapter.getDefaultAdapter(mContext) != null;
    }

    /**
     * 获取屏幕宽度
     *
     * @return 屏幕宽度
     */
    public static int getScreenWidth() {
        return mContext.getResources().getDisplayMetrics().widthPixels;
    }

    /**
     * 获取屏幕高度
     *
     * @return 屏幕高度
     */
    public static int getScreenHeight() {
        return mContext.getResources().getDisplayMetrics().heightPixels;
    }

    /**
     * dp 转 px
     *
     * @param dp dp值
     * @return px 值
     */
    public static float dpToPx(float dp) {
        DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics();
        return Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
    }

    /**
     * pz 转 dp
     *
     * @param px px值
     * @return dp值
     */
    public static float pxToDp(float px) {
        DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics();
        return Math.round(px / (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
    }

    /**
     * 安装 apk
     *
     * @param file 文件地址
     */
    public static void installAPK(File file) {
        if (file == null || !file.exists()) {
            return;
        }
        installAPK(FileUtils.pathToUri(file));
    }

    public static void installAPK(Uri uri){
        Intent intent = new Intent();
        intent.setAction(android.content.Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        mContext.startActivity(intent);
    }

    /**
     * 卸载指定包名的app
     *
     * @param packageName 包名
     */
    public static void uninstallApp(String packageName) {
        Uri packageURI = Uri.parse("package:" + packageName);
        Intent intent = new Intent(Intent.ACTION_DELETE, packageURI);
        mContext.startActivity(intent);
    }

    /**
     * 判断sd卡是否存在
     *
     * @return true存在 false不存在
     */
    public boolean existSDCard() {
        return Environment.getExternalStorageState()
                .equals(android.os.Environment.MEDIA_MOUNTED);
    }

    /**
     * 根据设备信息获取UUID
     *
     * @return uuid
     */
    public static String getUUID() {

        String serial = null;

        String m_szDevIDShort = "35" +
                Build.BOARD.length() % 10 + Build.BRAND.length() % 10 +
                Build.CPU_ABI.length() % 10 + Build.DEVICE.length() % 10 +
                Build.DISPLAY.length() % 10 + Build.HOST.length() % 10 +
                Build.ID.length() % 10 + Build.MANUFACTURER.length() % 10 +
                Build.MODEL.length() % 10 + Build.PRODUCT.length() % 10 +
                Build.TAGS.length() % 10 + Build.TYPE.length() % 10 +
                Build.USER.length() % 10; //13 位

//        try {
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//                serial = android.os.Build.getSerial();
//            } else {
//                serial = Build.SERIAL;
//            }
//            //API>=9 使用serial号
//            return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
//        } catch (Exception exception) {
//            //serial需要一个初始化
//            serial = "serial"; // 随便一个初始化
//        }

        serial = "zero-core";

        //使用硬件信息拼凑出来的15位号码
        return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
    }

    /**
     * 获取屏幕亮度
     */
    public static float getScreenBrightness(Activity activity) {
        return activity.getWindow().getAttributes().screenBrightness;
    }

    /**
     * 设置屏幕亮度
     */
    public static void setScreenBrightness(Activity activity, float brightness) {
        Window window = activity.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.screenBrightness = brightness;
        window.setAttributes(lp);
    }

    /**
     * 设置保持屏幕常亮
     */
    public static void setKeepScreenOn(Activity activity, boolean keep) {
        Window window = activity.getWindow();
        if (keep) {
            window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        } else {
            window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        }
    }
}
